package com.mayikt.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.bean.MeiteBeanUtils;
import com.mayikt.constants.Constants;
import com.mayikt.member.entity.UserDo;
import com.mayikt.member.feign.VerificationCodeServiceFeign;
import com.mayikt.member.input.dto.UserInDTO;
import com.mayikt.member.mapper.UserMapper;
import com.mayikt.member.service.UserService;
import com.mayikt.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Classname UserServiceImpl
 * @Description SpringBoot SpringCloud 构建微服务电商平台。
 * @Created by CHEN JIN LONG
 * @Date 2019/1/19 01:08
 * @Version 1.0
 */
@RestController
public class UserServiceImpl extends BaseApiService<JSONObject> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VerificationCodeServiceFeign verificationCodeServiceFeign;

    @Override
    @Transactional
    public BaseResponse<JSONObject> register(UserInDTO userInDTO, String registCode) {

        //参数验证
        if (StringUtils.isEmpty(userInDTO.getUSER_NAME()))
            return setResultError("用户名不能为空");
        String password = userInDTO.getPASSWORD();
        if (StringUtils.isEmpty(password))
            return setResultError("密码不能为空");
        //验证注册码

        BaseResponse<JSONObject> verificationCode = verificationCodeServiceFeign.verificationCode(userInDTO.getMOBILE(), registCode);

        if (!verificationCode.getCode().equals(Constants.HTTP_RES_CODE_200)) {
            return setResultError(verificationCode.getMsg());
        }

        String newPassword = Md5Utils.encryptPassword(password, "mayikt");
        userInDTO.setPASSWORD(newPassword);
        //调用数据库层插入数据
        return userMapper.register(MeiteBeanUtils.dtoToDO(userInDTO, UserDo.class)) > 0 ? setResultSuccess("注册成功") : setResultError("注册失败");
    }


}
